<template>
    <div class="pharmacy-management">
        <h4>药店管理</h4>

        <!-- 筛选区域 -->
        <el-card class="filter-card">
            <div class="filter-container">
                <div class="filter-item">
                    <span class="filter-label">药店名称：</span>
                    <el-input v-model="filterForm.keyword" style="width: 200px" placeholder="请输入药店名称" clearable
                        @input="handleFilterChange" @clear="handleFilterChange" />

                    <span class="filter-label">地区筛选：</span>
                    <el-select v-model="filterForm.province" placeholder="请选择省份" clearable style="width: 120px"
                        @change="handleProvinceChange">
                        <el-option v-for="province in provinceData" :key="province.value" :label="province.label"
                            :value="province.value" />
                    </el-select>

                    <el-select v-model="filterForm.city" placeholder="请选择市区" clearable style="width: 120px"
                        :disabled="!filterForm.province" @change="handleFilterChange">
                        <el-option v-for="city in cityData" :key="city.value" :label="city.label" :value="city.value" />
                    </el-select>

                    <span class="filter-label">或直接输入地址：</span>
                    <el-input v-model="filterForm.address" style="width: 180px" placeholder="请输入药店地址" clearable
                        @input="handleFilterChange" @clear="handleFilterChange" />
                </div>
                <br>
                <div class="filter-buttons">
                    <el-button type="primary" @click="handleFilterImmediate" :loading="loading">筛选</el-button>
                    <el-button type="default" @click="resetFilter" :disabled="loading">重置</el-button>
                    <el-tag v-if="hasActiveFilters" type="info" size="small">
                        已应用筛选条件
                    </el-tag>
                </div>
            </div>
        </el-card>

        <!-- 药店列表 -->
        <el-card class="list-card">
            <div class="list-header">
                <h5>药店列表</h5>
                <div class="list-actions">
                    <el-button type="success" @click="handleAdd" :disabled="loading || deleteLoading">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        新增药店
                    </el-button>
                    <el-button type="primary" @click="refreshData" :disabled="refreshLoading || deleteLoading"
                        :loading="refreshLoading">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        刷新数据
                    </el-button>

                </div>
            </div>

            <el-table ref="tableRef" :data="tableData" border style="width: 100%"
                @selection-change="handleSelectionChange" v-loading="loading" empty-text="暂无药店数据，请尝试调整筛选条件"
                :row-key="(row: any) => row.id" :default-sort="{ prop: 'uploadTime', order: 'descending' }">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="pharmacyName" label="药店名称" width="200" />
                <el-table-column label="列表图" width="120">
                    <template #default="scope">
                        <el-image :src="scope.row.pharmacyImage" :preview-src-list="[scope.row.pharmacyImage]"
                            fit="cover" style="width: 80px; height: 45px; border-radius: 4px;" />
                    </template>
                </el-table-column>
                <el-table-column prop="createdBy" label="上传人" width="100">
                    <template #default="scope">
                        {{ scope.row.createdBy || 'admin' }}
                    </template>
                </el-table-column>
                <el-table-column prop="uploadTime" label="上传时间">
                    <template #default="scope">
                        {{ moment(scope.row.uploadTime).format('YYYY-MM-DD HH:mm:ss') }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="260">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleViewDetail(scope.row)"
                            :disabled="deleteLoading">查看详情</el-button>
                        <el-button type="warning" size="small" @click="handleEdit(scope.row)"
                            :disabled="deleteLoading">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)" :loading="deleteLoading"
                            :disabled="deleteLoading">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <div class="pagination-left">
                    <el-checkbox v-model="selectAll" @change="handleSelectAll" :disabled="deleteLoading || loading">
                        全选
                    </el-checkbox>
                    <el-button type="danger" size="small" @click="handleBatchDelete"
                        :disabled="selectedRows.length === 0 || deleteLoading" :loading="deleteLoading">
                        批量删除 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
                    </el-button>
                    <el-divider direction="vertical" />
                    <span class="pagination-info">
                        共{{ page.pageCount }}页/{{ page.totalCount }}条数据
                        <el-tag v-if="selectedRows.length > 0" type="warning" size="small" style="margin-left: 8px;">
                            已选中 {{ selectedRows.length }} 条
                        </el-tag>
                        <el-tooltip content="快捷键： Ctrl+A(全选) | Delete(删除) | Esc(取消选择)" placement="top"
                            v-if="tableData.length > 0">
                            <el-icon style="margin-left: 8px; color: #909399; cursor: help;">
                                <QuestionFilled />
                            </el-icon>
                        </el-tooltip>
                    </span>
                </div>
                <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="page.totalCount"
                    layout="total, sizes, prev, pager, next, jumper" prev-text="上一页" next-text="下一页"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增药店' : '编辑药店'" width="800px"
            @close="resetForm">
            <el-button type="primary" @click="dialogVisible = false"
                style="float: right; margin-bottom: 20px;">返回</el-button>

            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right">
                <el-form-item label="药店名称" prop="pharmacyName">
                    <el-input v-model="formData.pharmacyName" placeholder="请输入..." />
                </el-form-item>

                <el-form-item label="列表图" prop="pharmacyImage">
                    <el-upload class="image-upload" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false"
                        :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
                        :on-progress="handleUploadProgress" :data="uploadData" name="imageFile" accept="image/*"
                        :multiple="false" drag v-loading="uploadLoading">
                        <div class="upload-area" :class="{ 'upload-success': uploadSuccess }">
                            <el-image v-if="formData.pharmacyImage" :src="formData.pharmacyImage" fit="cover"
                                style="width: 100%; height: 100%; border-radius: 4px;"
                                :preview-src-list="[formData.pharmacyImage]" preview-teleported />
                            <div v-else class="upload-placeholder">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                <div class="upload-text">点击上传图片</div>
                            </div>
                            <!-- 上传成功后的覆盖层 -->
                            <div v-if="formData.pharmacyImage" class="upload-overlay">
                                <div class="upload-success-icon">
                                    <el-icon color="#67c23a" size="24">
                                        <Check />
                                    </el-icon>
                                </div>
                            </div>
                        </div>
                    </el-upload>
                    <div class="upload-tip">建议尺寸120*90像素，大小不要超过1M</div>
                </el-form-item>

                <el-form-item label="是否推荐" prop="isRecommend">
                    <el-radio-group v-model="formData.isRecommend">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="所在地区" prop="pharmacyAreas">
                    <div class="area-selector">
                        <el-cascader v-model="areasCascaderValue" :options="regionData" :props="{
                            value: 'value',
                            label: 'label',
                            children: 'children'
                        }" placeholder="请选择省市区" clearable filterable style="width: 100%;" @change="handleAreaChange" />
                        <div v-if="formData.pharmacyAreas" class="area-display">
                            <el-tag type="info" size="small">已选择：{{ formData.pharmacyAreas }}</el-tag>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="详细地址" prop="pharmacyAddress">
                    <el-input v-model="formData.pharmacyAddress" placeholder="请输入..." />
                </el-form-item>

                <el-form-item label="药店电话" prop="pharmacyPhone">
                    <el-input v-model="formData.pharmacyPhone" placeholder="请输入..." />
                </el-form-item>

                <el-form-item label="药店介绍" prop="pharmacyDescription">
                    <div class="rich-text-editor">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" mode="default" />
                        <Editor style="height: 400px; overflow-y: hidden;" v-model="formData.pharmacyDescription"
                            :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="resetForm">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        {{ dialogType === 'add' ? '提交' : '更新' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="" width="900px">
            <div class="pharmacy-detail">
                <div class="detail-header">
                    <h2>{{ currentPharmacy.pharmacyName }}</h2>
                </div>

                <div class="detail-section">
                    <div class="detail-content">
                        <div class="detail-left">
                            <el-image :src="currentPharmacy.pharmacyImage"
                                style="width: 200px; height: 150px; border-radius: 8px;" fit="cover"
                                :preview-src-list="[currentPharmacy.pharmacyImage]" />
                        </div>
                        <div class="detail-right">
                            <div class="detail-info">
                                <p><strong>所在地区：</strong>{{ currentPharmacy.pharmacyAreas || (currentPharmacy.province ?
                                    codeToText[currentPharmacy.province] : '') + (currentPharmacy.city ?
                                        codeToText[currentPharmacy.city] : '') }}</p>
                                <p><strong>详细地址：</strong>{{ currentPharmacy.pharmacyAddress }}</p>
                                <p><strong>药店电话：</strong>{{ currentPharmacy.pharmacyPhone }}</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="detail-section">
                    <div class="pharmacy-intro">
                        <div v-if="currentPharmacy.pharmacyDescription || currentPharmacy.pharmacyIntroduction"
                            v-html="currentPharmacy.pharmacyDescription || currentPharmacy.pharmacyIntroduction"
                            class="rich-content">
                        </div>
                        <div v-else class="default-intro">
                            <p>北京金象大药房石佛营分店有限责任公司于2006年注册成立，为北京市大型医药零售连锁经营企业。公司以发展医药零售连锁为主业，拥有一个近20000平方米的现代化物流配送中心，经营涵盖化学药制剂、抗生素、医疗器械、生化药品、中成药、参茸、营养保健、中药饮片、医用图书等近万个品种。
                            </p>
                            <p>在北京开创24小时敞开式经营、电话咨询、预约订货、四环路以内免费送货上门、购药优惠券等，正明活动讲义诊，免费代煎药务，免费提供应药条等新的服务先河。2004年金象在北京推出金象会员积分卡和无风险退货、银行卡结算服务、免费提供取引图书阅等等一系列服务之举，不仅成为医药经营企业的服务典范，更使全象品牌、企业形象深植人心。
                            </p>
                            <p>北京金象大药房医药连锁有限责任公司被北京市商业委员会评选为北京市医药专业连锁的第一名，亲先跨入北区市流通业13强企业之一和全国连锁百强行列，成为北京市名优特药品经营品牌企业。《中国医药报》在国内大中城市对药店认知度的调查中，金象大药房在北京的提及率和首选率均达到90%以上。
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch, onBeforeUnmount, shallowRef, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Check, Loading, Refresh, QuestionFilled } from '@element-plus/icons-vue'
import { readB, writeB } from '@/api/http'
import moment from 'moment'
import { regionData, codeToText } from 'element-china-area-data'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { createEditor, createToolbar } from '@wangeditor/editor'
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 响应式数据
const tableData = ref<any[]>([])
const loading = ref(false)
const submitLoading = ref(false)
const uploadLoading = ref(false)
const uploadSuccess = ref(false)
const uploadHistory = ref<string[]>([])
const dialogVisible = ref(false)
const deleteLoading = ref(false)
const refreshLoading = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const tableRef = ref()
const selectedRows = ref<any[]>([])
const selectAll = ref(false)
const currentPharmacy = ref<any>({})

// 富文本编辑器相关
const editorRef = shallowRef()

// 工具栏配置
const toolbarConfig = {
    excludeKeys: ['group-video', 'insertVideo', 'uploadVideo', 'codeBlock', 'group-indent']
}

// 编辑器配置
const editorConfig = {
    placeholder: '请输入药店描述...',
    MENU_CONF: {
        uploadImage: {
            server: 'http://localhost:5023/api/Carousel/UploadCarouselImage/upload-image?bucketName=image&prefix=pharmacy',
            fieldName: 'imageFile',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
            },
            onSuccess(file: any, res: any) {
                console.log('富文本图片上传成功', file, res)
            },
            onFailed(file: any, res: any) {
                console.log('富文本图片上传失败', file, res)
                ElMessage.error('富文本图片上传失败')
            },
            onProgress(progress: number) {
                console.log('富文本图片上传进度:', progress)
            }
        }
    }
}

// 省市联动数据（保留用于筛选功能）
const provinceData = ref(regionData)
const cityData = ref<any[]>([])

// 表单中的省市区级联数据
const formCityData = ref<any[]>([])
const formDistrictData = ref<any[]>([])

// 级联选择器的值（数组形式：[provinceCode, cityCode, districtCode]）
const areasCascaderValue = ref<string[]>([])

// 筛选表单
const filterForm = reactive({
    keyword: '',     // 药店名称搜索
    province: '',    // 省份筛选
    city: '',        // 市级筛选
    address: ''      // 直接地址搜索
})

// 分页参数
const page = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    pageCount: 0
})

// 表单数据
const formData = reactive({
    id: '',
    pharmacyName: '',
    pharmacyImage: '',
    isRecommend: false,
    pharmacyAreas: '', // 最终存储的地区字符串
    province: '', // 省份代码
    city: '', // 市级代码
    district: '', // 区县代码
    pharmacyAddress: '',
    pharmacyDescription: '',
    pharmacyPhone: ''
})

// 表单验证规则
const formRules: FormRules = {
    pharmacyName: [
        { required: true, message: '请输入药店名称', trigger: 'blur' }
    ],
    pharmacyImage: [
        { required: true, message: '请上传列表图', trigger: 'change' }
    ],
    pharmacyAreas: [
        { required: true, message: '请选择所在地区', trigger: 'change' }
    ],
    pharmacyAddress: [
        { required: true, message: '请输入详细地址', trigger: 'blur' }
    ],
    pharmacyPhone: [
        { required: true, message: '请输入药店电话', trigger: 'blur' }
    ]
}

// 上传相关
const uploadUrl = 'http://47.95.68.41:4560/api/Carousel/UploadCarouselImage/upload-image?bucketName=image&prefix=pharmacy'
const uploadHeaders = {
    'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
}
const uploadData = {
    bucketName: 'image',
    prefix: 'pharmacy'
}

// 模拟数据
const mockData = [
    {
        id: '1',
        pharmacyName: '北京金象大药房石佛营分店',
        pharmacyImage: 'https://via.placeholder.com/120x90',
        isRecommend: true,
        pharmacyAreas: '北京市朝阳区',
        pharmacyAddress: '北京市朝阳区石佛营路5号',
        pharmacyDescription: '<p>北京金象大药房医药连锁有限责任公司于2006年注册成立，为北京市大型医药零售连锁经营企业。</p>',
        pharmacyPhone: '010-12345678',
        // 保留旧字段用于兼容显示
        province: '110000',
        city: '110105',
        pharmacyIntroduction: '<p>北京金象大药房医药连锁有限责任公司于2006年注册成立，为北京市大型医药零售连锁经营企业。</p>',
        createdBy: 'admin',
        uploadTime: '2019-02-07 21:00:00'
    },
    {
        id: '2',
        pharmacyName: '全象大药房石佛营分店',
        pharmacyImage: 'https://via.placeholder.com/120x90',
        isRecommend: false,
        pharmacyAreas: '北京市朝阳区',
        pharmacyAddress: '北京市朝阳区石佛营路10号',
        pharmacyDescription: '<p>专业的药品零售连锁企业...</p>',
        pharmacyPhone: '010-87654321',
        // 保留旧字段用于兼容显示
        province: '110000',
        city: '110105',
        pharmacyIntroduction: '<p>专业的药品零售连锁企业...</p>',
        createdBy: 'admin',
        uploadTime: '2019-02-07 21:00:00'
    }
]

// 级联选择器改变事件
const handleAreaChange = (value: string[]) => {
    console.log('级联选择器改变:', value)

    if (value && value.length > 0) {
        // 更新表单数据
        formData.province = value[0] || ''
        formData.city = value[1] || ''
        formData.district = value[2] || ''

        // 构建地区字符串
        const areaNames: string[] = []
        if (value[0] && codeToText[value[0]]) {
            areaNames.push(codeToText[value[0]])
        }
        if (value[1] && codeToText[value[1]]) {
            areaNames.push(codeToText[value[1]])
        }
        if (value[2] && codeToText[value[2]]) {
            areaNames.push(codeToText[value[2]])
        }

        formData.pharmacyAreas = areaNames.join('')
        console.log('更新后的pharmacyAreas:', formData.pharmacyAreas)
    } else {
        // 清空选择
        formData.province = ''
        formData.city = ''
        formData.district = ''
        formData.pharmacyAreas = ''
    }
}

// 根据地区代码设置级联选择器的值
const setAreasCascaderValue = (province: string, city: string, district?: string) => {
    const cascaderValue: string[] = []

    if (province) cascaderValue.push(province)
    if (city) cascaderValue.push(city)
    if (district) cascaderValue.push(district)

    areasCascaderValue.value = cascaderValue
    console.log('设置级联选择器的值:', cascaderValue)
}

// 根据地区名称查找对应的地区代码（用于数据回显）
const findAreaCodesByName = (areaName: string) => {
    const result = { province: '', city: '', district: '' }

    if (!areaName) return result

    // 遍历省份
    for (const province of regionData) {
        if (areaName.includes(province.label)) {
            result.province = province.value

            // 遍历市级
            if (province.children) {
                for (const city of province.children) {
                    if (areaName.includes(city.label)) {
                        result.city = city.value

                        // 遍历区县
                        if (city.children) {
                            for (const district of city.children) {
                                if (areaName.includes(district.label)) {
                                    result.district = district.value
                                    break
                                }
                            }
                        }
                        break
                    }
                }
            }
            break
        }
    }

    console.log('根据地区名称查找代码:', areaName, '结果:', result)
    return result
}

// 构建地址筛选参数用于API调用
const buildAddressFilter = () => {
    // 优先使用直接输入的地址
    if (filterForm.address && filterForm.address.trim()) {
        console.log('使用直接输入的地址:', filterForm.address.trim())
        return filterForm.address.trim()
    }

    // 否则使用省市选择器构建地址
    let addressFilter = ''

    // 如果有省份选择，添加省份名称
    if (filterForm.province && codeToText[filterForm.province]) {
        addressFilter += codeToText[filterForm.province]
    }

    // 如果有市级选择，添加市级名称
    if (filterForm.city && codeToText[filterForm.city]) {
        addressFilter += codeToText[filterForm.city]
    }

    console.log('构建地址筛选参数:', addressFilter)
    return addressFilter
}

// 实时筛选处理
const handleFilterChange = () => {
    // 防抖处理，避免频繁调用API
    if (filterChangeTimer) {
        clearTimeout(filterChangeTimer)
    }

    filterChangeTimer = setTimeout(() => {
        console.log('实时筛选触发:', filterForm)
        page.PageIndex = 1  // 重置到第一页
        getPharmacyList()
    }, 300)
}

// 防抖定时器
let filterChangeTimer: number | null = null

// 检查是否有激活的筛选条件
const hasActiveFilters = computed(() => {
    return !!(filterForm.keyword || filterForm.province || filterForm.city || filterForm.address)
})

// 省市联动方法（保留用于筛选功能）
const handleProvinceChange = (provinceCode: string) => {
    filterForm.city = ''

    if (provinceCode) {
        const province = provinceData.value.find((item: any) => item.value === provinceCode)
        if (province && province.children) {
            cityData.value = province.children
        } else {
            cityData.value = []
        }
    } else {
        cityData.value = []
    }

    // 触发实时筛选
    handleFilterChange()
}



// 获取药店列表
const getPharmacyList = async () => {
    loading.value = true
    try {
        // 准备API参数（根据后端API文档调整）
        const apiParams: { [key: string]: any } = {
            PageIndex: page.PageIndex,
            PageSize: page.PageSize,
            PharmacyName: filterForm.keyword || '',
            PharmacyAddress: buildAddressFilter() || ''
        }

        // 过滤空参数
        Object.keys(apiParams).forEach(key => {
            if (apiParams[key] === '' || apiParams[key] === null || apiParams[key] === undefined) {
                delete apiParams[key]
            }
        })

        console.log('获取药店列表参数:', apiParams)

        // 调用真实API
        const response = await readB('/api/Drugstore/GetDrugstoreList/list', {
            params: apiParams
        })

        console.log('药店列表API响应:', response)

        if (response && response.data && response.data.code === 200) {
            // 处理成功响应
            const data = response.data.data || []
            tableData.value = data
            page.totalCount = response.data.totalCount || data.length
            page.pageCount = response.data.pageCount || Math.ceil(page.totalCount / page.PageSize)

            // 清除选择状态
            selectedRows.value = []
            selectAll.value = false
            if (tableRef.value) {
                tableRef.value.clearSelection()
            }

            console.log(`成功加载 ${data.length} 条药店数据`)
        } else {
            // API返回错误
            const errorMessage = response?.data?.message || '获取数据失败'
            ElMessage.error(errorMessage)
            tableData.value = []
            page.totalCount = 0
            page.pageCount = 0
        }

        loading.value = false
    } catch (error: any) {
        console.error('获取药店列表失败:', error)

        let errorMessage = '获取数据失败'
        if (error.response) {
            const status = error.response.status
            if (status === 401) {
                errorMessage = '未授权，请重新登录'
            } else if (status === 403) {
                errorMessage = '没有权限访问此数据'
            } else if (status === 500) {
                errorMessage = '服务器内部错误'
            } else {
                errorMessage = error.response.data?.message || `HTTP ${status} 错误`
            }
        } else if (error.message) {
            errorMessage = error.message
        }

        ElMessage.error(errorMessage)
        tableData.value = []
        page.totalCount = 0
        page.pageCount = 0
        loading.value = false
    }
}

// 筛选处理（立即触发）
const handleFilterImmediate = () => {
    console.log('立即筛选触发:', filterForm)
    page.PageIndex = 1
    getPharmacyList()
}

// 重置筛选条件
const resetFilter = () => {
    filterForm.keyword = ''
    filterForm.province = ''
    filterForm.city = ''
    filterForm.address = ''
    cityData.value = []
    page.PageIndex = 1
    getPharmacyList()
}

// 新增
const handleAdd = () => {
    dialogType.value = 'add'
    resetForm()
    dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
    dialogType.value = 'edit'

    // 设置表单数据
    Object.assign(formData, {
        id: row.id,
        pharmacyName: row.pharmacyName,
        pharmacyImage: row.pharmacyImage,
        isRecommend: row.isRecommend,
        pharmacyAreas: row.pharmacyAreas || (row.province && row.city ? `${codeToText[row.province]}${codeToText[row.city]}` : ''),
        province: row.province || '',
        city: row.city || '',
        district: row.district || '',
        pharmacyAddress: row.pharmacyAddress,
        pharmacyDescription: row.pharmacyDescription || row.pharmacyIntroduction || '',
        pharmacyPhone: row.pharmacyPhone
    })

    // 设置级联选择器的值
    if (row.province || row.city) {
        // 如果有直接的省市代码，直接使用
        setAreasCascaderValue(row.province, row.city, row.district)
    } else if (formData.pharmacyAreas) {
        // 如果只有地区名称，尝试解析
        const areaCodes = findAreaCodesByName(formData.pharmacyAreas)
        formData.province = areaCodes.province
        formData.city = areaCodes.city
        formData.district = areaCodes.district
        setAreasCascaderValue(areaCodes.province, areaCodes.city, areaCodes.district)
    } else {
        // 清空级联选择器
        areasCascaderValue.value = []
    }

    dialogVisible.value = true
}

// 查看详情
const handleViewDetail = (row: any) => {
    currentPharmacy.value = { ...row }
    detailDialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除以下药店吗？\n\n药店名称：${row.pharmacyName}\n所在地区：${row.pharmacyAreas || '未知'}\n\n此操作不可恢复！`,
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: false,
                customClass: 'delete-confirm-dialog'
            }
        )

        console.log('删除药店:', row)

        // 设置删除加载状态
        deleteLoading.value = true

        // 使用批量删除API删除单个药店（传入一个ID的数组）
        const response = await writeB.post('/api/Drugstore/BatchDeleteDrugstore/batch-delete', {
            drugstoreIds: [row.id]
        })

        console.log('删除API响应:', response)

        if (response && response.data && response.data.code === 200) {
            ElMessage.success(`删除成功：${row.pharmacyName}`)
            // 刷新列表
            await getPharmacyList()
        } else {
            const errorMessage = response?.data?.message || '删除失败'
            ElMessage.error(errorMessage)
        }

        deleteLoading.value = false
    } catch (error: any) {
        deleteLoading.value = false

        if (error === 'cancel') {
            // 用户取消删除
            return
        }

        console.error('删除失败:', error)
        let errorMessage = '删除失败'

        if (error.response) {
            const status = error.response.status
            const data = error.response.data

            if (status === 400) {
                errorMessage = data?.message || '请求参数错误'
            } else if (status === 401) {
                errorMessage = '未授权，请重新登录'
            } else if (status === 403) {
                errorMessage = '没有权限删除此数据'
            } else if (status === 404) {
                errorMessage = '要删除的数据不存在'
            } else if (status === 500) {
                errorMessage = '服务器内部错误'
            } else {
                errorMessage = data?.message || `HTTP ${status} 错误`
            }
        } else if (error.message) {
            errorMessage = error.message
        }

        ElMessage.error(errorMessage)
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的数据')
        return
    }

    // 构建删除列表信息
    const deleteList = selectedRows.value.map(row => `• ${row.pharmacyName} (${row.pharmacyAreas || '未知地区'})`).join('\n')
    const confirmMessage = `确定要删除以下 ${selectedRows.value.length} 家药店吗？\n\n${deleteList}\n\n此操作不可恢复！`

    try {
        await ElMessageBox.confirm(confirmMessage, '批量删除确认', {
            confirmButtonText: `确定删除 ${selectedRows.value.length} 条`,
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: false,
            customClass: 'batch-delete-confirm-dialog'
        })

        console.log('批量删除药店:', selectedRows.value)

        // 提取所有选中ID
        const drugstoreIds = selectedRows.value.map(row => row.id)

        console.log('批量删除ID列表:', drugstoreIds)

        // 设置删除加载状态
        deleteLoading.value = true

        // 调用批量删除API
        const response = await writeB.post('/api/Drugstore/BatchDeleteDrugstore/batch-delete', {
            drugstoreIds: drugstoreIds
        })

        console.log('批量删除API响应:', response)

        if (response && response.data && response.data.code === 200) {
            ElMessage.success(`批量删除成功，共删除 ${drugstoreIds.length} 家药店`)
            // 清空选中状态
            selectedRows.value = []
            selectAll.value = false
            if (tableRef.value) {
                tableRef.value.clearSelection()
            }
            // 刷新列表
            await getPharmacyList()
        } else {
            const errorMessage = response?.data?.message || '批量删除失败'
            ElMessage.error(errorMessage)
        }

        deleteLoading.value = false
    } catch (error: any) {
        deleteLoading.value = false

        if (error === 'cancel') {
            // 用户取消删除
            return
        }

        console.error('批量删除失败:', error)
        let errorMessage = '批量删除失败'

        if (error.response) {
            const status = error.response.status
            const data = error.response.data

            if (status === 400) {
                errorMessage = data?.message || '请求参数错误'
            } else if (status === 401) {
                errorMessage = '未授权，请重新登录'
            } else if (status === 403) {
                errorMessage = '没有权限执行批量删除'
            } else if (status === 500) {
                errorMessage = '服务器内部错误'
            } else {
                errorMessage = data?.message || `HTTP ${status} 错误`
            }
        } else if (error.message) {
            errorMessage = error.message
        }

        ElMessage.error(errorMessage)
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        // 准备API参数
        const apiParams = {
            pharmacyName: formData.pharmacyName,
            pharmacyImage: formData.pharmacyImage,
            isRecommend: formData.isRecommend,
            pharmacyAreas: formData.pharmacyAreas,
            pharmacyAddress: formData.pharmacyAddress,
            pharmacyDescription: formData.pharmacyDescription,
            pharmacyPhone: formData.pharmacyPhone
        }

        console.log('提交参数:', apiParams)

        try {
            // 调用实际API
            let response
            if (dialogType.value === 'add') {
                // 新增药店
                response = await writeB.post('/api/Drugstore/AddDrugstore/add', apiParams)
            } else {
                // 修改药店，需要包含id参数
                const updateParams = {
                    id: formData.id,
                    ...apiParams
                }
                response = await writeB.post('/api/Drugstore/UpdateDrugstore/update', updateParams)
            }

            console.log('API响应:', response)

            // 处理API响应
            if (response && response.data && response.data.code === 200) {
                ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
                submitLoading.value = false
                dialogVisible.value = false
                // 刷新列表
                await getPharmacyList()
            } else {
                const errorMessage = response?.data?.message || '操作失败'
                ElMessage.error(errorMessage)
                submitLoading.value = false
            }
        } catch (apiError: any) {
            console.error('API调用失败:', apiError)
            let errorMessage = '操作失败'

            if (apiError.response) {
                // HTTP错误响应
                const status = apiError.response.status
                const data = apiError.response.data

                if (status === 400) {
                    errorMessage = data?.message || '请求参数错误'
                } else if (status === 401) {
                    errorMessage = '未授权，请重新登录'
                } else if (status === 403) {
                    errorMessage = '没有权限执行此操作'
                } else if (status === 500) {
                    errorMessage = '服务器内部错误'
                } else {
                    errorMessage = data?.message || `HTTP ${status} 错误`
                }
            } else if (apiError.message) {
                errorMessage = apiError.message
            }

            ElMessage.error(errorMessage)
            submitLoading.value = false
        }
    } catch (validationError) {
        console.error('表单验证失败:', validationError)
        submitLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.assign(formData, {
        id: '',
        pharmacyName: '',
        pharmacyImage: '',
        isRecommend: false,
        pharmacyAreas: '',
        province: '',
        city: '',
        district: '',
        pharmacyAddress: '',
        pharmacyDescription: '',
        pharmacyPhone: ''
    })

    // 清空级联选择器
    areasCascaderValue.value = []

    uploadSuccess.value = false
}

// 显示上传成功的图片
const showUploadedImage = (imageUrl: string) => {
    // 创建一个图片预览对话框
    ElMessageBox.alert(
        `<div style="text-align: center;">
            <img src="${imageUrl}" style="max-width: 100%; max-height: 400px; border-radius: 8px;" />
            <p style="margin-top: 10px; color: #67c23a;">图片上传成功！</p>
            <div style="margin-top: 10px; font-size: 12px; color: #909399;">
                <p>上传时间: ${new Date().toLocaleString()}</p>
            </div>
        </div>`,
        '上传成功',
        {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            customClass: 'upload-success-dialog'
        }
    )
}

// 重新上传图片
const reuploadImage = () => {
    formData.pharmacyImage = ''
    ElMessage.info('请重新选择图片上传')
}

// 选择历史图片
const selectHistoryImage = (url: string) => {
    formData.pharmacyImage = url
    ElMessage.success('已选择历史图片')
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
    selectAll.value = selection.length === tableData.value.length && tableData.value.length > 0
}

const handleSelectAll = (value: boolean) => {
    if (tableRef.value) {
        if (value) {
            tableRef.value.clearSelection()
            tableData.value.forEach(row => {
                tableRef.value.toggleRowSelection(row, true)
            })
        } else {
            tableRef.value.clearSelection()
        }
    }
}

// 分页处理
const handleSizeChange = (size: number) => {
    console.log('分页大小改变:', size)
    page.PageSize = size
    page.PageIndex = 1
    getPharmacyList()
}

const handleCurrentChange = (current: number) => {
    console.log('当前页改变:', current)
    page.PageIndex = current
    getPharmacyList()
}

// 无闪动刷新数据
const refreshData = async () => {
    // 防抖处理，避免重复点击
    if (refreshLoading.value) {
        return
    }

    console.log('手动刷新数据')
    refreshLoading.value = true

    try {
        // 准备API参数（根据后端API文档调整）
        const apiParams: { [key: string]: any } = {
            PageIndex: page.PageIndex,
            PageSize: page.PageSize,
            PharmacyName: filterForm.keyword || '',
            PharmacyAddress: buildAddressFilter() || ''
        }

        // 过滤空参数
        Object.keys(apiParams).forEach(key => {
            if (apiParams[key] === '' || apiParams[key] === null || apiParams[key] === undefined) {
                delete apiParams[key]
            }
        })

        console.log('刷新数据参数:', apiParams)

        // 调用真实API（不触发全局loading状态）
        const response = await readB('/api/Drugstore/GetDrugstoreList/list', {
            params: apiParams
        })

        console.log('刷新数据API响应:', response)

        if (response && response.data && response.data.code === 200) {
            // 处理成功响应 - 无缝更新数据
            const data = response.data.data || []
            tableData.value = data
            page.totalCount = response.data.totalCount || data.length
            page.pageCount = response.data.pageCount || Math.ceil(page.totalCount / page.PageSize)

            // 保持当前选择状态不变，除非数据已不存在
            const currentSelectedIds = selectedRows.value.map(row => row.id)
            const newData = data.filter((item: any) => currentSelectedIds.includes(item.id))

            if (newData.length !== selectedRows.value.length) {
                // 如果选中的数据有变化，清除选择状态
                selectedRows.value = []
                selectAll.value = false
                if (tableRef.value) {
                    tableRef.value.clearSelection()
                }
            }

            console.log(`刷新成功，更新 ${data.length} 条药店数据`)
            ElMessage.success('数据刷新成功')
        } else {
            // API返回错误
            const errorMessage = response?.data?.message || '刷新数据失败'
            ElMessage.error(errorMessage)
        }
    } catch (error: any) {
        console.error('刷新数据失败:', error)

        let errorMessage = '刷新数据失败'
        if (error.response) {
            const status = error.response.status
            if (status === 401) {
                errorMessage = '未授权，请重新登录'
            } else if (status === 403) {
                errorMessage = '没有权限访问此数据'
            } else if (status === 500) {
                errorMessage = '服务器内部错误'
            } else {
                errorMessage = error.response.data?.message || `HTTP ${status} 错误`
            }
        } else if (error.message) {
            errorMessage = error.message
        }

        ElMessage.error(errorMessage)
    } finally {
        refreshLoading.value = false
    }
}

// 键盘快捷键支持
const handleKeyboardShortcuts = (event: KeyboardEvent) => {
    // Ctrl+D 或 Cmd+D: 批量删除
    if ((event.ctrlKey || event.metaKey) && event.key === 'd') {
        event.preventDefault()
        if (selectedRows.value.length > 0 && !deleteLoading.value) {
            handleBatchDelete()
        }
    }
    // Delete 键: 批量删除
    else if (event.key === 'Delete') {
        event.preventDefault()
        if (selectedRows.value.length > 0 && !deleteLoading.value) {
            handleBatchDelete()
        }
    }
    // Ctrl+A 或 Cmd+A: 全选
    else if ((event.ctrlKey || event.metaKey) && event.key === 'a' && !loading.value) {
        event.preventDefault()
        selectAll.value = true
        handleSelectAll(true)
    }
    // Escape: 取消选择
    else if (event.key === 'Escape') {
        selectAll.value = false
        handleSelectAll(false)
    }
}

// 上传处理
const beforeUpload = (file: File) => {
    console.log('准备上传文件:', {
        name: file.name,
        type: file.type,
        size: file.size,
        lastModified: file.lastModified
    })
    console.log('上传URL:', uploadUrl)
    console.log('上传Headers:', uploadHeaders)
    console.log('上传Data:', uploadData)

    // 检查文件类型
    const isImage = file.type.startsWith('image/')
    const isValidFormat = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)
    const isLt1M = file.size / 1024 / 1024 < 1

    if (!isImage || !isValidFormat) {
        ElMessage.error('上传图片只能是 JPG/PNG/GIF/WEBP 格式!')
        return false
    }
    if (!isLt1M) {
        ElMessage.error('上传图片大小不能超过 1MB!')
        return false
    }

    uploadLoading.value = true
    uploadSuccess.value = false
    return true
}

const handleUploadSuccess = (response: any, file: File) => {
    uploadLoading.value = false

    console.log('上传成功响应 - 完整响应:', response)
    console.log('上传成功响应 - response.code:', response?.code)
    console.log('上传成功响应 - response.data:', response?.data)
    console.log('上传成功文件:', file)

    // 先检查是否有响应
    if (!response) {
        ElMessage.error('上传失败：服务器无响应')
        return
    }

    // 检查响应码，同时兼容不同的响应格式（有些 API 可能不返回 code 字段）
    const isSuccess = response.code === 200 || response.status === 200 || (!response.code && !response.error)

    if (isSuccess) {
        // 尝试从不同的位置获取图片URL
        const imageUrl = response.data?.url || response.data?.imageUrl || response.url || response.data || response

        console.log('提取到的图片URL:', imageUrl)

        if (imageUrl && typeof imageUrl === 'string' && imageUrl.startsWith('http')) {
            formData.pharmacyImage = imageUrl

            // 添加到上传历史
            uploadHistory.value.unshift(imageUrl)
            if (uploadHistory.value.length > 5) {
                uploadHistory.value.pop()
            }

            // 显示上传成功状态
            uploadSuccess.value = true
            setTimeout(() => {
                uploadSuccess.value = false
            }, 2000)

            // 显示上传成功的图片
            showUploadedImage(imageUrl)

            ElMessage.success('图片上传成功')
        } else {
            console.error('API返回格式不正确:', response)
            console.error('提取到的imageUrl:', imageUrl, typeof imageUrl)
            ElMessage.error('图片上传失败：返回格式错误')
        }
    } else {
        console.error('上传失败，响应码不正确:', response)
        ElMessage.error(response?.message || response?.msg || '图片上传失败')
    }
}

const handleUploadError = (error: any, file?: any) => {
    uploadLoading.value = false
    uploadSuccess.value = false
    console.error('图片上传失败 - Error:', error)
    console.error('图片上传失败 - File:', file)

    // 尝试从错误对象中提取更多信息
    let errorMessage = '网络错误'

    if (error?.response) {
        const status = error.response.status
        const statusText = error.response.statusText
        errorMessage = `HTTP ${status}: ${statusText}`

        if (status === 400) {
            errorMessage = '请求参数错误，请检查图片格式和大小'
        } else if (status === 401) {
            errorMessage = '未授权，请重新登录'
        } else if (status === 413) {
            errorMessage = '文件太大，请选择小于1MB的图片'
        } else if (status === 500) {
            errorMessage = '服务器内部错误'
        }
    } else if (error?.message) {
        errorMessage = error.message
    }

    ElMessage.error(`图片上传失败: ${errorMessage}`)
}

const handleUploadProgress = (event: any) => {
    // 上传进度处理
    if (event.percent) {
        console.log(`上传进度: ${event.percent}%`)
    }
}

// 富文本编辑器创建后的回调
const handleCreated = (editor: any) => {
    editorRef.value = editor
}

// 组件销毁前清理编辑器和定时器
onBeforeUnmount(() => {
    // 清理富文本编辑器
    const editor = editorRef.value
    if (editor != null) {
        editor.destroy()
    }

    // 清理筛选防抖定时器
    if (filterChangeTimer) {
        clearTimeout(filterChangeTimer)
        filterChangeTimer = null
    }

    // 移除键盘事件监听
    document.removeEventListener('keydown', handleKeyboardShortcuts)
})

// 监听关键字变化已由实时筛选处理，此处不再需要
// watch(() => filterForm.keyword, (newVal, oldVal) => {
//     if (newVal !== oldVal) {
//         setTimeout(() => {
//             handleFilterImmediate()
//         }, 300)
//     }
// })

// 监听省份变化
watch(() => filterForm.province, (newVal) => {
    handleProvinceChange(newVal)
})

// 初始化
onMounted(() => {
    getPharmacyList()
    // 添加键盘事件监听
    document.addEventListener('keydown', handleKeyboardShortcuts)
})
</script>

<style scoped>
.pharmacy-management {
    padding: 20px;
}

.pharmacy-management h4 {
    margin: 0 0 20px 0;
    font-size: 20px;
    color: #333;
}

/* 筛选区域样式 */
.filter-card {
    margin-bottom: 20px;
}

.filter-container {
    padding: 10px 0;
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 15px;
    flex-wrap: wrap;
}

.filter-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
}

/* 列表区域样式 */
.list-card {
    margin-bottom: 20px;
}

.list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.list-header h5 {
    margin: 0;
    font-size: 16px;
    color: #333;
}

.list-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

/* 分页区域样式 */
.pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;
}

.pagination-left {
    display: flex;
    align-items: center;
    gap: 15px;
}

.pagination-info {
    color: #909399;
    font-size: 14px;
}

/* 上传区域样式 */
.image-upload {
    width: 200px;
}

.upload-area {
    width: 200px;
    height: 120px;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
}

.upload-area:hover {
    border-color: #409eff;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #999;
}

.upload-placeholder .el-icon {
    font-size: 28px;
    margin-bottom: 8px;
}

.upload-text {
    font-size: 14px;
}

.upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
}

.upload-area:hover .upload-overlay {
    opacity: 1;
}

.upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #999;
}

/* 富文本编辑器样式 */
.rich-text-editor {
    border: 1px solid #ccc;
    border-radius: 4px;
    overflow: hidden;
}

.rich-text-editor:focus-within {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 对话框样式 */
.dialog-footer {
    text-align: right;
}

/* 详情页样式 */
.pharmacy-detail {
    padding: 20px;
}

.detail-header {
    margin-bottom: 20px;
    text-align: center;
}

.detail-header h2 {
    margin: 0;
    color: #333;
    font-size: 24px;
}

.detail-section {
    margin-bottom: 30px;
}

.detail-content {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
}

.detail-left {
    flex-shrink: 0;
}

.detail-right {
    flex: 1;
}

.detail-info p {
    margin: 10px 0;
    font-size: 16px;
    line-height: 1.6;
}

.detail-info strong {
    color: #333;
}

.pharmacy-intro {
    line-height: 1.6;
    color: #666;
}

.pharmacy-intro p {
    margin-bottom: 15px;
}

/* 富文本内容样式 */
.rich-content {
    line-height: 1.6;
    color: #666;
}

.rich-content p {
    margin-bottom: 15px;
    margin-top: 0;
}

.rich-content h1,
.rich-content h2,
.rich-content h3,
.rich-content h4,
.rich-content h5,
.rich-content h6 {
    margin-top: 20px;
    margin-bottom: 10px;
    color: #333;
}

.rich-content ul,
.rich-content ol {
    margin-bottom: 15px;
    padding-left: 20px;
}

.rich-content img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 10px 0;
}

.rich-content blockquote {
    margin: 15px 0;
    padding: 10px 15px;
    background-color: #f8f9fa;
    border-left: 4px solid #409eff;
    color: #666;
}

.rich-content code {
    background-color: #f1f2f3;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
    color: #e74c3c;
}

.rich-content pre {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
    overflow-x: auto;
    margin: 15px 0;
}

.rich-content a {
    color: #409eff;
    text-decoration: none;
}

.rich-content a:hover {
    text-decoration: underline;
}

.default-intro p {
    margin-bottom: 15px;
    margin-top: 0;
}

/* 上传成功消息样式 */
.upload-success-message {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(103, 194, 58, 0.9);
    color: white;
    padding: 10px 15px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    z-index: 10;
}

/* 图片信息显示样式 */
.image-info {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 8px;
    padding: 8px;
    background-color: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e9ecef;
}

/* 上传历史样式 */
.upload-history {
    margin-top: 12px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e9ecef;
}

.history-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
}

.history-list {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.history-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    padding: 8px;
    background: white;
    border-radius: 4px;
    border: 1px solid #ddd;
    transition: all 0.3s;
}

.history-item:hover {
    border-color: #409eff;
    box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.history-item .el-button {
    font-size: 12px;
    padding: 4px 8px;
}

/* 上传成功对话框样式 */
:deep(.upload-success-dialog) {
    .el-message-box__content {
        padding: 20px;
    }

    .el-message-box__message {
        text-align: center;
    }
}

/* 地区选择器样式 */
.area-selector {
    width: 100%;
}

.area-display {
    margin-top: 8px;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
}

.area-display .el-tag {
    margin: 0;
}

/* 级联选择器的下拉面板样式 */
:deep(.el-cascader-panel) {
    .el-cascader-node {
        padding: 8px 12px;
    }

    .el-cascader-node:hover {
        background-color: #f5f7fa;
    }

    .el-cascader-node.is-active {
        color: #409eff;
        font-weight: 600;
    }
}

/* 级联选择器输入框样式 */
:deep(.el-cascader) {
    .el-input__wrapper {
        transition: all 0.3s;
    }

    .el-input__wrapper:hover {
        border-color: #c0c4cc;
    }

    .el-input__wrapper.is-focus {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }
}

/* 筛选按钮区域样式 */
.filter-buttons {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.filter-buttons .el-button {
    transition: all 0.3s;
}

.filter-buttons .el-tag {
    font-weight: 500;
}

/* 删除确认对话框样式 */
:deep(.delete-confirm-dialog) {
    .el-message-box__content {
        padding: 20px;
        font-size: 14px;
        line-height: 1.6;
        white-space: pre-line;
    }

    .el-message-box__message {
        color: #606266;
    }

    .el-button--primary.is-plain {
        background-color: #f56c6c;
        border-color: #f56c6c;
        color: white;
    }

    .el-button--primary.is-plain:hover {
        background-color: #f78989;
        border-color: #f78989;
    }
}

:deep(.batch-delete-confirm-dialog) {
    .el-message-box__content {
        padding: 20px;
        font-size: 14px;
        line-height: 1.6;
        white-space: pre-line;
        max-height: 300px;
        overflow-y: auto;
    }

    .el-message-box__message {
        color: #606266;
    }

    .el-button--primary.is-plain {
        background-color: #f56c6c;
        border-color: #f56c6c;
        color: white;
    }

    .el-button--primary.is-plain:hover {
        background-color: #f78989;
        border-color: #f78989;
    }
}

/* 删除加载状态优化 */
.el-button.is-loading {
    pointer-events: none;
}

/* 表格行的删除状态 */
.el-table__row.is-deleting {
    background-color: #fdf6ec;
    opacity: 0.7;
}

/* 批量操作区域样式 */
.pagination-left {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

.pagination-left .el-divider--vertical {
    height: 20px;
    margin: 0 4px;
}

.pagination-info {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #909399;
}

/* 操作按钮组样式 */
.list-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

.list-actions .el-button {
    display: flex;
    align-items: center;
    gap: 4px;
}

.list-actions .el-tag {
    display: flex;
    align-items: center;
    gap: 4px;
}
</style>